<?php
/**
 * Created by PhpStorm.
 * User: luo
 * Date: 2018/9/26
 * Time: 22:30
 */

namespace app\models;

use app\tools\Tool;
use Yii;
use app\tools\Time;
use app\models\User;
use app\models\UserLogin;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Inflector;

/**
 * Class Base
 * @property $id
 * @property $user_id
 * @property $created_at
 * @property $updated_at
 * @property User $user
 * @package app\models
 */
class Base extends ActiveRecord
{

    const PAGE_SIZE = 20;

    /**
     * 全局统一的状态标识，无特殊情况，统一按此标准执行
     */
    const STATUS_ON  = 1;
    const STATUS_OFF = 0;
    const STATUS_DEL = -1;

    public function init()
    {
        parent::init();
        $this->on(self::EVENT_BEFORE_VALIDATE, [$this, 'onSetDefaultAttributes']);
        if($this->hasMethod('onRemoveUrlPrefix')){
            $this->on(self::EVENT_BEFORE_VALIDATE, [$this, 'onRemoveUrlPrefix']);
        }
    }

    public function onSetDefaultAttributes(){
        if(
            $this->hasAttribute('user_id') &&
            ($this->user_id === null || $this->user_id === '') &&
            Yii::$app->has('user') &&
            !Yii::$app->user->isGuest){

            $this->user_id = Yii::$app->user->id;
        }

        if($this->hasAttribute('created_at') && ($this->created_at === null) && $this->isNewRecord){
            $this->created_at = time();
        }

        if($this->hasAttribute('updated_at') && ($this->updated_at === null)){
            $this->updated_at = time();
        }
    }

    public function getUser(){
        /* @var $this \yii\db\ActiveRecord */
        return $this->hasOne(User::class, ['id'=>'user_id']);
    }

    public function getAdmin(){
        /* @var $this \yii\db\ActiveRecord */
        return $this->hasOne(User::class, ['id'=>'admin_id']);
    }

    public function showErrors(){
        $errors = '';
        foreach ($this->errors as $v){
            foreach ($v as $v2){
                $errors .= $v2."\n";
            }
        }
        return $errors;
    }

    /**
     * 用于自动生成创建时间的展示
     * @param $type string friendly short
     * @return string
     */
    public function showShortTime(){
        return date('Y-m-d', $this->created_at);

    }

    public function showTime(){
        return date('Y-m-d H:i', $this->created_at);
    }

    public function showFansTime(){
        return date('Y-m-d', $this->created_at);
    }

    public function showExpireTime(){
        return date('Y-m-d H:i:s', $this->expire_time);
    }

    public function showStartTime(){
        return date('Y-m-d H:i:s', $this->start_time);
    }

    public function showCreatedAt(){
        return date('Y-m-d H:i:s', $this->created_at);
    }

    public function showUpdatedAt($type = 'friendly'){
        return date('Y-m-d H:i:s', $this->updated_at);
    }

    public function showCreateUsername(){
        if($this->user_id && $this->user){
            return $this->user->showUsername();
        }else{
            return '';
        }
    }

    public function showCreateUserIcon(){
        if($this->user_id && $this->user){
            return $this->user->showIcon();
        }else{
            return '';
        }
    }

    public function showCreateNickname(){
        if($this->user_id && $this->user){
            return $this->user->showNickname();
        }else{
            return '';
        }
    }

    public function showAdminNickname(){
        if($this->admin_id && $this->admin){
            return $this->admin->showNickname();
        }else{
            return '';
        }
    }

    /**
     * @param Base[] $model_list
     * @param string[] $fields
     * @return array
     */
    public static function buildParamsList($model_list, $fields){
        $list = [];
        foreach ($model_list as $k=>$v){
            $list[] = self::buildParam($v, $fields);
        }
        return $list;
    }

    public function buildParams($fields){
        return Base::buildParam($this, $fields);
    }

    /**
     * @param $model self
     * @param $fields
     * @return array
     */
    public static function buildParam($model, $fields){
        $data = [];
        foreach ($fields as $v) {
            $method_name = 'show' . Inflector::camelize($v);
            if (method_exists($model, $method_name)) {
                $data[$v] = $model->$method_name();
            } elseif ($model->hasAttribute($v)) {
                $data[$v] = $model->$v;
            } elseif (property_exists($model, $v)) {
                $data[$v] = $model->$v;
            } else {
                $data[$v] = '';
            }
        }
        return $data;
    }

    //发推送
    public function sendPush($user_id=0, $from_user_name='匿名者', $type=1) {
        //device_type: 1:安卓  2:ios
        //type: 1:点赞  2:评论
        $message = "";
        if ($type == 1) {
            $message = "用户" . $from_user_name . "赞了您的评论";
        } else {
            $message = "你的评论收到1条最新回复，立即查看";
        }
        $user_login = UserLogin::find()->where(['user_id' => $user_id])->orderBy("id desc")->one();
        if (empty($user_id) || empty($user_login)) {
            return "信息错误";
        }
        $device = $user_login->device;
        $device_type = strstr($device,"okhttp") ? 1 : 2;
        $appkey = $device_type == 1 ? "5bd7b14fb465f525230003ff" : "5bd7b12cf1f55684520004cd";
        $appSecret = $device_type == 1 ? "8idhnizs3nrwouwl5ubydcyrsvzgkr7n" : "xaafcpntioem0nhix1ihu2z4yarhubt1";
        $url = "https://msgapi.umeng.com/api/send";
        $payload_body = [
            "ticker"      => "11",
            "title"       => "消息通知",
            "text"        => $message,
            "after_open"  => "go_custom",
            "custom"      => "jiaju://msgNotify",
            "play_vibrate" => "false",
            "play_lights" => "false",
            "play_sound" => "true"
        ];
        $payload_android = [
            "display_type" => "notification",
            "body" => $payload_body,
        ];

        $alert = [
            //"title"     => "消息通知",
            "subtitle"  => "消息通知",
            "body"      => $message,
        ];
        $aps = [
            "alert" => $alert,
        ];
        $payload_ios = [
            "aps" => $aps,
            "target" => "jiaju://msgNotify",
        ];

        $policy = [
            "expire_time" => date("Y-m-d H:i:s", time()+120),
        ];
        $post_arr = [
            "appkey" => $appkey,
            "timestamp" => time(),
            "type" => "customizedcast",
            //"type" => "unicast",
            //"production_mode" => "false",
            //"device_tokens" => "Au_cuWwJLNClgBsHxjwPdI0CDN9_nPwee4xn6ZYTxzaV",
            "alias" => $user_id,
            "alias_type" => "kUMessageAliasTypeUserId",
            "payload" => $device_type ==1 ? $payload_android : $payload_ios,
            "policy" => $policy,
            "description" => "111",
        ];
        $post_data = json_encode($post_arr);
        $mysign = md5("POST" . $url . $post_data . $appSecret);
        $url = $url . "?sign=" . $mysign;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErrNo = curl_errno($ch);
        $curlErr = curl_error($ch);
        curl_close($ch);

        $result_data = [
            'httpCode' => $httpCode,
            'result' => $result,
            'curlErrNo' => $curlErrNo,
            'curlErr' => $curlErr,
        ];
        return $result_data;
    }
}
